package middleware

import (
	"github.com/go-kit/kit/log"
	"http_rest/register/service"
	"time"
)

type loggingMiddleware struct {
	service.Service
	logger log.Logger
}

//递归
func LoggingMiddleware(logger log.Logger) service.ServiceMiddleware{
	return func(service service.Service) service.Service {
		return loggingMiddleware{service, logger}
	}
}

func (mw loggingMiddleware) Add(a,b int) (ret int){
	defer func(begin time.Time) {
		mw.logger.Log(
			"function", "Add",
			"a", a,
			"b", b,
			"result", ret,
			"took", time.Since(begin),
			)
	}(time.Now())
	ret = mw.Service.Add(a,b)
	return ret
}

func (mw loggingMiddleware) Subtract(a,b int) (ret int){
	defer func(begin time.Time) {
		mw.logger.Log(
			"function", "Subtract",
			"a", a,
			"b", b,
			"result", ret,
			"took", time.Since(begin),
		)
	}(time.Now())
	ret = mw.Service.Subtract(a,b)
	return ret
}

func (mw loggingMiddleware) Multiply(a,b int) (ret int){
	defer func(begin time.Time) {
		mw.logger.Log(
			"function", "Multiply",
			"a", a,
			"b", b,
			"result", ret,
			"took", time.Since(begin),
		)
	}(time.Now())
	ret = mw.Service.Multiply(a,b)
	return ret
}

func (mw loggingMiddleware) Divide(a,b int) (ret int, err error){
	defer func(begin time.Time) {
		mw.logger.Log(
			"function", "Divide",
			"a", a,
			"b", b,
			"result", ret,
			"took", time.Since(begin),
		)
	}(time.Now())
	ret, err = mw.Service.Divide(a,b)
	return ret, err
}

func (mw loggingMiddleware) HealthCheck() (result bool){
	defer func(begin time.Time) {
		mw.logger.Log(
			"function", "HealthCheck",
			"result", result,
			"took", time.Since(begin),
		)
	}(time.Now())
	result = mw.Service.HealthCheck()
	return
}